// 游戏统计管理器
class GameStatsManager {
    constructor() {
        this.stats = this.loadStats();
        this.currentGameStartTime = null;
        this.currentGameTimer = null;
    }

    // 加载统计数据
    loadStats() {
        const savedStats = localStorage.getItem('snake_game_stats');
        if (savedStats) {
            return JSON.parse(savedStats);
        }
        
        // 默认统计数据
        return {
            totalGames: 0,
            totalPlayTime: 0, // 单位：秒
            highScore: 0,
            achievements: 0,
            lastPlayed: null,
            gameRecords: []
        };
    }

    // 保存统计数据
    saveStats() {
        localStorage.setItem('snake_game_stats', JSON.stringify(this.stats));
    }

    // 开始游戏计时
    startGameTimer() {
        this.currentGameStartTime = Date.now();
        this.currentGameTimer = setInterval(() => {
            this.updateDisplay();
        }, 1000);
    }

    // 结束游戏计时
    endGameTimer() {
        if (this.currentGameStartTime) {
            const gameDuration = Math.floor((Date.now() - this.currentGameStartTime) / 1000);
            this.stats.totalPlayTime += gameDuration;
            this.currentGameStartTime = null;
        }
        
        if (this.currentGameTimer) {
            clearInterval(this.currentGameTimer);
            this.currentGameTimer = null;
        }
    }

    // 记录游戏开始
    recordGameStart() {
        this.stats.totalGames++;
        this.stats.lastPlayed = new Date().toISOString();
        this.startGameTimer();
        this.saveStats();
    }

    // 记录游戏结束
    recordGameEnd(score = 0) {
        this.endGameTimer();
        
        if (score > this.stats.highScore) {
            this.stats.highScore = score;
        }
        
        // 记录游戏详情
        this.stats.gameRecords.push({
            date: new Date().toISOString(),
            score: score,
            duration: this.getCurrentGameDuration()
        });
        
        // 只保留最近50条记录
        if (this.stats.gameRecords.length > 50) {
            this.stats.gameRecords = this.stats.gameRecords.slice(-50);
        }
        
        this.saveStats();
        this.updateDisplay();
    }

    // 获取当前游戏时长
    getCurrentGameDuration() {
        if (!this.currentGameStartTime) return 0;
        return Math.floor((Date.now() - this.currentGameStartTime) / 1000);
    }

    // 格式化时间显示
    formatTime(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;
        
        if (hours > 0) {
            return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        } else {
            return `${minutes}:${secs.toString().padStart(2, '0')}`;
        }
    }

    // 更新显示
    updateDisplay() {
        const totalGamesEl = document.getElementById('total-games');
        const highScoreEl = document.getElementById('high-score');
        const totalTimeEl = document.getElementById('total-time');
        const achievementsEl = document.getElementById('achievements');

        if (totalGamesEl) {
            totalGamesEl.textContent = this.stats.totalGames.toLocaleString();
        }
        
        if (highScoreEl) {
            highScoreEl.textContent = this.stats.highScore.toLocaleString();
        }
        
        if (totalTimeEl) {
            totalTimeEl.textContent = this.formatTime(this.stats.totalPlayTime);
        }
        
        if (achievementsEl) {
            achievementsEl.textContent = this.stats.achievements;
        }
    }

    // 重置统计数据
    resetStats() {
        if (confirm('确定要重置所有游戏统计数据吗？此操作不可撤销！')) {
            this.stats = {
                totalGames: 0,
                totalPlayTime: 0,
                highScore: 0,
                achievements: 0,
                lastPlayed: null,
                gameRecords: []
            };
            this.saveStats();
            this.updateDisplay();
            alert('统计数据已重置！');
        }
    }

    // 获取统计数据
    getStats() {
        return {
            ...this.stats,
            formattedTotalTime: this.formatTime(this.stats.totalPlayTime)
        };
    }

    // 添加成就
    addAchievement() {
        this.stats.achievements++;
        this.saveStats();
        this.updateDisplay();
    }
}

// 创建全局统计管理器实例
window.gameStats = new GameStatsManager();

// 页面加载时初始化显示
document.addEventListener('DOMContentLoaded', function() {
    if (window.gameStats) {
        window.gameStats.updateDisplay();
    }
});